<template>
  <el-table :data="tableData" style="width: 100%" :row-class-name="tableRowClassName" #default="scope">
    <el-table-column prop="id" label="AGV ID" width="180" />
    <el-table-column prop="ip" label="2.4g" width="180" />
    <el-table-column prop="ip5" label="5g" />
    <!-- <el-table-column #default="scope" label="是否在线"> {{ scope.row.isOnline }} &nbsp;&nbsp; {{ scope.row.isOnline5 }}</el-table-column> -->
    <el-table-column fixed="right" label="切换ip" width="200">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="setipFn(scope.row.ip)">切换WIFI</el-button>
        <el-button link type="primary" size="small" @click="setip5gFn(scope.row.ip)">切换5G</el-button>
      </template>
    </el-table-column>
  </el-table>
</template>
<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { getIpApi } from '../api/agv'
import { ElMessage } from 'element-plus'
import axios from "axios";
interface User {
  id: string
  ip: string
  ip5: string
  isOnline?: boolean
  isOnline5?: boolean
}

const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: User
  rowIndex: number
}) => {
  if (row.isOnline) {
    // return 'success-row'
  }
  if (row.isOnline5) {
    // return 'success-row'
  }
  return ''
}
let tableData = ref([])

let getIpFn = async () => {
  let res = await getIpApi()
  tableData.value = res.data
}

async function setipFn(ip) {
  console.log(ip)
  setIp(ip, "setip")
}
function setip5gFn(ip) {
  console.log(ip)
  setIp(ip, "setip5")
}
async function setIp(ip, apiurl) {
  try {
    let res = await axios.post('http://' + ip + ':3333/api/' + apiurl, { ip, apiurl }, { timeout: 1000 })
      .catch(err => {
        console.log(err)
        setTimeout(() => {
          axios.post('http://' + ip + ':3333/api/' + apiurl, { ip, apiurl }, { timeout: 1000 }).then(e => {
            console.log(e)
          }).catch(e => {
            console.log("err", e)
          })
        }, 2000)
      })
    // console.log(res.data.msg)

    // if (res.data.code == 200) {
    //   ElMessage({
    //     showClose: true,
    //     message: res.data.msg,
    //     type: 'success',
    //   })
    // } else {
    //   ElMessage({
    //     showClose: true,
    //     message: "切换失败",
    //     type: 'error',
    //   })
    // }
  } catch {
    // ElMessage({
    //   showClose: true,
    //   message: "ip不在线，请手动检查是否切换成功",
    //   type: 'warning',
    // })
  }
}

onMounted(async () => {
  getIpFn()
  setInterval(() => {
    getIpFn()
  }, 2000);
})
</script>

<style>
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.el-table .error-row {
  --el-table-tr-bg-color: red;
}
</style>
